package com.itlong.cloud.controller.h5;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.PaySourceEnum;
import com.itlong.cloud.enumerate.ThirdPartPayTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode.MiniProgramErrorCodeEnum;
import com.itlong.cloud.paymenthub.IAccountBalanceServiceClient;
import com.itlong.cloud.paymenthub.IWeChatPayServiceClient;
import com.itlong.cloud.project.property.IPropertyAccountServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *     H5物业增值控制器
 * </desc>
 *
 * @create  2019/05/27
 */
@RestController
@RequestMapping("/H5/propertyValue")
public class H5PropertyValueController extends BaseController{

    private static final Logger LOG = LoggerFactory.getLogger(H5PropertyValueController.class);

    @Autowired
    private IPropertyAccountServiceClient iPropertyAccountServiceClient;

    @Autowired
    IWeChatPayServiceClient wechatPayServiceClient;

    @Autowired
    IAccountBalanceServiceClient iAccountBalanceServiceClient;

    /**
     * <desc>
     *      查询全部欠费账单
     * <desc/>
     *
     * @param projectId 项目编号
     * @param deviceId 设备序号
     * @param deviceType 设备类型
     * @param roomId 房间编号
     * @param userId 用户编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/05/28
     */
    @RequestMapping(path = "getAllArrearsBill")
    @UnAuthAccessRequired
    @ResponseBody
    public MessageVO getAllArrearsBill(String projectId, String deviceId, String deviceType, String roomId, String userId) {
        try {
            //项目编号判断
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            //设备序号
            if (StringUtils.isBlank(deviceId)){
                return new MessageVO(MiniProgramErrorCodeEnum.H5_DEVICEUNIQUE_EMPTY_ERR.getErrorCode());
            }
            //设备类型
            if (StringUtils.isBlank(deviceType)){
                return new MessageVO(MiniProgramErrorCodeEnum.H5_DEVICETYPE_EMPTY_ERR.getErrorCode());
            }
            //房间编号同用户编号
            if (StringUtils.isBlank(roomId) && StringUtils.isBlank(userId)){
                return new MessageVO(MiniProgramErrorCodeEnum.H5_ROOMID_USERID_EMPTY_ERR.getErrorCode());
            }

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyAccountServiceClient.getAllArrearsBill(projectId,deviceId,deviceType,roomId,userId));
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【H5_物业增值_查询全部欠费账单】查询全部欠费账单失败"), e);
        }
    }

    /**
     * <desc>
     *      创建并获取临时通行账单
     * <desc/>
     *
     * @param projectId 项目编号
     * @param userId 用户编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/05/28
     */
    @RequestMapping(path = "createTemporaryPassageFee")
    @UnAuthAccessRequired
    @ResponseBody
    public MessageVO createTemporaryPassageBill(String projectId, String userId) {
        try {
            //项目编号判断
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyAccountServiceClient.createTemporaryPassageBill(projectId,userId));
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【H5_物业增值_创建并获取临时通行账单】创建临时通行账单失败"), e);
        }
    }

    /**
     * <desc>
     *      查询用户历史账单
     * <desc/>
     *
     * @param projectId 项目编号
     * @param roomId 房间编号
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/05/28
     */
    @RequestMapping(path = "getUserBillListH5")
    @UnAuthAccessRequired
    @ResponseBody
    public MessageVO getUserBillListH5(String projectId, String roomId) {
        try {
            //项目编号判断
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(roomId)){
                return new MessageVO(MiniProgramErrorCodeEnum.VISIT_ROOM_IS_NULL.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iPropertyAccountServiceClient.getUserBillListH5(projectId,roomId));
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【H5_物业增值_查询用户历史账单】查询用户历史账单失败"), e);
        }
    }

    /**
     * <desc>
     *      h5支付-调微信后台统一下单接口/商户后台保存订单
     * <desc/>
     *
     * @param total 支付金额
     * @param userId 用户编号
     * @param billsId 账单编号
     * @param feeType 缴费类型 1物业费 2维修费 3临时车缴费 4月卡缴费
     * @param deviceUnique 设备编号
     * @return 标准化响应结果
     * @author Qiang.S
     * @createDate 2018/5/30
     */
    @LoggerInfo(operateDesc = LogDescConstant.WECHAT_PAYMENT_ORDER)
    @RequestMapping(path = "/order")
    @UnAuthAccessRequired
    @ResponseBody
    public MessageVO saveOrder(String total,String userId,String billsId, String feeType, String deviceUnique,String openId) {
        //LOG.info("======saveOrder参数：total：" + total);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("total",total);
            if(StringUtils.isNotEmpty(feeType)){
                params.put("feeType",feeType);
            }else{
                feeType = "";
            }
            if (StringUtils.isBlank(billsId)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //校验第三方支付管理微信支付是否被禁用
            if(wechatPayServiceClient.getThirdPayStatus(ThirdPartPayTypeEnum.WECHAT_PAY.getType())==0){
                return new MessageVO(AppErrorCodeEnum.NOT_ALLOWED_WEICHAT_TRADE.getErrorCode());
            }
            //查询该账单是否已经被完成
            if(wechatPayServiceClient.getBillStatus(billsId)>0){
                return new MessageVO(AppErrorCodeEnum.BILL_PAY_SUCCESS.getErrorCode());
            }
            //查询账单的金额，校验入参金额
            String totalDB = wechatPayServiceClient.getBillTotal(billsId,1);
            if(StringUtils.isNotEmpty(totalDB)){
                BigDecimal totalCheck = new BigDecimal(total);
                BigDecimal totalDBCheck = new BigDecimal(totalDB);
                if(totalCheck.compareTo(totalDBCheck)!=0){
                    return new MessageVO(AppErrorCodeEnum.BILL_PAY_TOTAL_IS_NOT_SAME.getErrorCode());
                }
            }

            Map<Object,Object> resultMap = wechatPayServiceClient.saveOrder(total,userId,billsId,feeType,openId, PaySourceEnum.WECHAT_OFFICIAL_SOURCE.getType(),deviceUnique,null,request.getRemoteAddr(),null,null);
//            if(resultMap.size()==9 || resultMap.size()==8){
            ErrorCode errorCode = BaseErrorCodeEnum.SUCCESS.getErrorCode();
            return new MessageVO(errorCode,resultMap);
//            } else {
//                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), resultMap);
//            }

        } catch (Exception e) {
            throw new DataAccessException("【H5_微信支付】API返回的数据异常", e);
        }

    }

    /**
     * <desc>
     *      检测订单状态是否为完成
     * <desc/>
     *
     * @param
     * @return  标准化响应结果
     * @author Juguang.S
     * @createDate 2019/05/29
     */
    @ResponseBody
    @UnAuthAccessRequired
    @RequestMapping("/checkTradeSuccess")
    public MessageVO checkTradeSuccess(String billsId,String tradeId) {
        try {
            //LOG.info("【H5检测订单状态是否为完成】"+"billsId:"+billsId+"----tradeId:"+tradeId);
            if (StringUtils.isBlank(billsId)||StringUtils.isBlank(tradeId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String,Object> map = new HashMap<>();
            if(iAccountBalanceServiceClient.checkTradeSuccess(billsId,"",tradeId)){
                //2代表订单支付成功  1代表支付未成功
                map.put("paymentStatus","2");
            }else {
                map.put("paymentStatus","1");
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        } catch (Exception e) {
            throw new DataAccessException("【微信】检测订单状态是否为完成失败", e);
        }
    }
}